<?php
namespace app\common\logic\cast\news;



use app\common\logic\cast\Base;
use app\common\utils\Utils;
use fast\Http;
use think\Db;
use think\exception\ValidateException;
use think\Log;


/**
 * Created by PhpStorm.
 * User: yangchunfu
 * Date: 2019/12/24
 * Time: 4:36 PM
 * 栏目
 */

class Wx2Super extends Base
{
    protected $apiHref = 'https://api03.6bqb.com/wechat/article/search';
    private $apikey = '71BC2571794B8849E2F37CBCF2014BF4';

    public function __construct($options= [], $tag = 'wx_super')
    {
        $search = config('site.wxsearch');
        $key = array_rand($search,1);
        $value = $search[$key];
        $options = array_merge([
            'apikey' => $this->apikey,
            'keyword' => $value,
        ], $options);

        parent::__construct($options, $tag);
    }

    /**
     * 获取插入字段
     * id,url,title,publishDate,imageUrls
     */
    public function getField($v) {
        $v = $v['article'];
        $data['news_id'] = MD5($v['url']); //根据url生成 唯一id
        $detail = $this->createUrl($v['url']);
        $data['url'] = $detail['url'];
        $data['content'] = $detail['html'];
        $data['title'] = $v['title'];
        $data['publishDate'] = time();
        $data['is_self'] = 1;
        if (isset($v['imgs']) && is_array($v['imgs'])) {
            $data['imageUrls'] = array_pop($v['imgs']);
        } else {
            $data['imageUrls'] = '';
        }

        return $data;
    }

    //重新生成url
    public function createUrl($link) {
        $options = [
            'apikey' => $this->apikey,
            'url' => $link
        ];

        $res = Http::get('https://api03.6bqb.com/wechat/article/detail', $options);
        $res = json_decode($res, true);
        $res = $res['data'];
        $html = $res['contentHtml'];
        $url = 'http://app.aebrowser.cn/api/v1_web.web_service/news';

        return [
            'url' => $url,
            'html' => $html
        ];
    }

    /**
     * 写入数据库方法
     */
    public function add($data) {
        //标示是类名小写
        if (!$this->tag) {
            throw new ValidateException('标识必须传递');
        }
        //首先判断是否已经写入数据库
        $db = Db::name('self_news');
        foreach ($data as $k => $v) {
            try {
                if ($db->where(['news_id' => $v['news_id']])->whereOr([
                        'title' => $v['title']
                    ])->count() > 0) {
                    continue;
                }
                $v['tag'] = $this->tag;
                $start = time() - 6 * 3600;
                $v['rand'] = rand($start, time());
                $v['createtime'] = time();
                $db->insert($v);
                $id = $db->getLastInsID();
                $url = $v['url'] . '?id=' .$id;

                $db->where(['id'=> $id])->setField('url', $url);
            } catch (\Exception $e) {
                Log::write($e->getMessage(), 'insertnews');
            }
        }

        return true;
    }

}